package com.rtx.edi.platform.handler;

import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.rtx.edi.model.api.po.PlApiMappingStructure;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class TargetFieldHandle {
	static Logger  log = LoggerFactory.getLogger(TargetFieldHandle.class);

	public static String handleFieldScript(String targetJSONString,List<PlApiMappingStructure> structureList) throws Exception {
		JSONObject targetJSON = JSONUtil.parseObj(targetJSONString);
		for(PlApiMappingStructure structure:structureList) {
			
			//执行 目标值处理脚本
			handleFieldScript(structure,targetJSONString,targetJSON);
		}
		
		return targetJSON.toJSONString(0);
	}
	
	private static void handleSerialnumber(PlApiMappingStructure structure) {
		if("serialnumber".equals(structure.getMappingType())) {
			
		}
	}

	public static String handleTargetDefaultValue(String targetJSONString,List<PlApiMappingStructure> structureList) throws Exception {
		JSONObject targetJSON = JSONUtil.parseObj(targetJSONString);
		for(PlApiMappingStructure structure:structureList) {
			
			//执行 目标值处理脚本
			handleTargetDefaultValue(structure,targetJSONString,targetJSON);
		}
		
		return targetJSON.toJSONString(0);
	}
	
	/**
	 * 设置目标报文默认值
	 * @param structure
	 * @param targetJSONString
	 * @param targetJSON
	 */
	private static void handleTargetDefaultValue(PlApiMappingStructure structure,String targetJSONString,JSONObject targetJSON) {
		try {
			String targetDefaultValue = structure.getTargetDefaultValue();
			if(!StringUtils.hasLength(targetDefaultValue)) {
				return;
			}

			String fullpath = structure.getFieldFullPath();
			
			if(fullpath.contains("数组")) {

				String[] array = fullpath.replace("root.", "").split("数组");
				JSONObject target = JSONUtil.parseObj(targetJSONString);
				String arrayStr =   target.getByPath(array[0]).toString();
				JSONArray jsonArray = JSONUtil.parseArray(arrayStr);
				for(int i=0;i<jsonArray.size();i++) {
					try {
						String path = fullpath.replace("root.", "").replace("数组", "["+i+"]");
						Object orivalue = JSONUtil.getByPath(targetJSON, path);
						if(null == orivalue || orivalue instanceof String) {
							if(null == orivalue || !StringUtils.hasLength(orivalue+"")) {
								if("uid".equals(targetDefaultValue)) {
									JSONUtil.putByPath(targetJSON, path, UUID.randomUUID().toString());
								}else  {
									JSONUtil.putByPath(targetJSON, path, targetDefaultValue);
								}
								
							}
						}
					} catch (Exception e) {
						log.error("", e);
					}
				}
			}else {
				Object orivalue = JSONUtil.getByPath(targetJSON, fullpath.replace("root.", ""));
				if(orivalue instanceof String) {
					if("uid".equals(targetDefaultValue)) {
						JSONUtil.putByPath(targetJSON, fullpath.replace("root.", ""), UUID.randomUUID().toString());
					}else {
						JSONUtil.putByPath(targetJSON, fullpath.replace("root.", ""), targetDefaultValue);
					}
				}
			}
		} catch (Exception e) {
			log.error("", e);
		}
	}
	
	/**
	 * 执行 目标值处理脚本 
	 * @param structure
	 * @param targetJSONString
	 * @param targetJSON
	 */
	private static void handleFieldScript(PlApiMappingStructure structure,String targetJSONString,JSONObject targetJSON) {
		try {
			String fieldScript = structure.getFieldScript();
			if(!StringUtils.hasLength(fieldScript)) {
				return;
			}
			ScriptEngineManager manager = new ScriptEngineManager();
			ScriptEngine engine = manager.getEngineByName("JavaScript");
			engine.put("targetJSONString", targetJSONString);
			StringBuffer script = new StringBuffer();

			String fullpath = structure.getFieldFullPath();

			if(fullpath.contains("数组")) {

				String[] array = fullpath.split("数组");
				JSONObject target = JSONUtil.parseObj(targetJSONString);
				String arrayStr =   (String) target.getByPath(array[0]);
				JSONArray jsonArray = JSONUtil.parseArray(arrayStr);
				for(int i=0;i<jsonArray.size();i++) {
					try {
						script.append("var detail = JSON.parse("+jsonArray.getStr(i)+");");
						engine.eval(script.toString());
						String result = String.valueOf(engine.get("result"));
						if(StringUtils.hasLength(result)) {
							String path = fullpath.replace("数组", "["+i+"]");
							JSONUtil.putByPath(targetJSON, path, result);
						}
					} catch (Exception e) {
						log.error("", e);
					}
				}
			}else {
				script.append("var root = JSON.parse(targetJSONString);");
				script.append(fieldScript);

				engine.eval(script.toString());
				String result = String.valueOf(engine.get("result"));
				if(StringUtils.hasLength(result)) {
					JSONUtil.putByPath(targetJSON, fullpath.replace("root.", ""), result);
				}
			}
		} catch (Exception e) {
			log.error("", e);
		}
	}
}
